var express = require('express');
var router = express.Router();
var models = require('../models')
var Op = models.Sequelize.Op

/* GET right info */
router.get('/', async function (req, res, next) {
    try {
        if (req.query.rightId) {
            var rightId = req.query.rightId
            var right = await models.Right.findOne({
                where: { [Op.and]: [{ id: `${rightId}` }] }
            })
            res.json({ right })
        } else if (req.query.key) {
            var key = req.query.key
            var right = await models.Right.findOne({
                where: { [Op.and]: [{ key: `${key}` }] }
            })
            if (right) {
                res.json({ right })
            } else {
                res.json({ msg: "不存在此权限" })
            }

        } else {
            var rights = await models.Right.findAll()
            res.json({ rights })
        }
    } catch (e) {
        console.log(e);
    }
});

router.get('/:id', async function (req, res, next) {
    try {
        var right = await models.Right.findByPk(req.params.id)
        if (right) {
            res.json({ right })
        }
    } catch (error) {
        console.log(error);
        res.json({ error })
    }
});


// 获取用户提交的信息并插入数据库
router.post('/', async function (req, res, next) {
    const { key, title, pagePermission, grade } = JSON.parse(req.query.data)
    try {
        var right = await models.Right.create({
            key, title, pagePermission, grade
        })
        res.json({ right: right })
    } catch (e) {
        console.log(e)
    }
})

// 修改权限信息
router.put('/:id', async function (req, res, next) {
    const id = req.params.id
    const { key, title, pagePermission, grade } = JSON.parse(req.query.data)
    try {
        var right = await models.Right.update({
            key, title, pagePermission, grade
        }, { where: { id } })

        res.json({ right })
    } catch (e) {
        console.log(e)
    }
})

// 修改权限状态
router.put('/pagePermission/:id', async function (req, res, next) {
    const id = req.params.id
    const pagePermission = JSON.parse(req.query.pagePermission)
    // console.log(roleState);
    try {
        var right = await models.Right.update({
            pagePermission
        }, { where: { id } })
        res.json({ right })
    } catch (e) {
        console.log(e)
    }
})

// 删除权限信息
router.delete('/:id', async function (req, res, next) {
    const id = req.params.id
    var right = await models.Right.findByPk(id)
    if (right) {
        right.destroy()
        res.json({ msg: '删除成功' })
    } else {
        res.json({ msg: '不存在该数据' })
    }
})

module.exports = router;
